package com.yupi.springbootinit.bizmq;

import com.rabbitmq.client.Channel;
import com.yupi.springbootinit.constant.CommonConstant;
import com.yupi.springbootinit.constant.FileConstant;
import com.yupi.springbootinit.exception.BusinessException;
import com.yupi.springbootinit.manager.AiManager;
import com.yupi.springbootinit.manager.WenxinManager;
import com.yupi.springbootinit.model.entity.Chart;
import com.yupi.springbootinit.model.enums.GenChartStrategyEnum;
import com.yupi.springbootinit.service.ChartService;
import com.yupi.springbootinit.common.ErrorCode;
import com.yupi.springbootinit.utils.ChartUtil;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.messaging.handler.annotation.Header;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * @TODO 消费者
 */
@Component
@Slf4j
public class BiMessageConsumer {

    @Resource
    private ChartService chartService;
    @Resource
    private AiManager aiManager;
    @Resource
    private WenxinManager wenxinManager;

    //指定程序监听的消息队列和确认机制
    @SneakyThrows   // 抛异常
    @RabbitListener(queues = {BiMqConstant.BI_QUEUE_NAME}, ackMode = "MANUAL")
    public void receiveMessage(String message, Channel channel, @Header(AmqpHeaders.DELIVERY_TAG) long deliveryTag) {
        if (StringUtils.isBlank(message)) {
            /* 消息拒绝（标签，拒绝该标签的所有信息，true被拒绝的消息将重新排队false直接丢弃） */
            channel.basicNack(deliveryTag, false, false);
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "消息为空");
        }
        Long chartId = Long.parseLong(message);     // String转Long
        Chart chart = chartService.getById(chartId);
        if (chart == null) {
            channel.basicNack(deliveryTag, false, false);
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR, "图表为空");
        }
        //先修改图表任务状念为”执行中”。等执行成功后，修收为”已完成”、保执行钻米；执行失败斤，状修收为”双，记录任务失败信园：
        Chart updateChart = new Chart();
        updateChart.setId(chart.getId());
        updateChart.setStatus(FileConstant.RUNNING);
        boolean b = chartService.updateById(updateChart);   // 修改数据库状态为执行中
        if (!b) {
            channel.basicNack(deliveryTag, false, false);
            handleChartUpdateError(chart.getId(), "图表状态更改失败");
            return;
        }

        // 调用 AI
        log.info("调用 鱼聪明AI");
        String inputCsvMessage = buildUserInput(chart);
        String result = aiManager.doChat(CommonConstant.BI_MODEL_ID, inputCsvMessage);
        // String result = "【【【【【sh【【【【【ide";
        log.info("AI 生成的语句：\n{}", result);
        String[] splits = result.split("【【【【【");
        if (splits.length != 3) {
            channel.basicNack(deliveryTag, false, false);
            handleChartUpdateError(chart.getId(), "AI 生成错误");
            return;
        }

        // 第一段是空，所以从第二段开始取
        String genChart = splits[1].trim();
        String genResult = splits[2].trim();
        genChart = ChartUtil.compressJson(genChart);

        updateChart.setStatus(FileConstant.SUCCEED);
        updateChart.setGenChart(genChart);
        updateChart.setGenResult(genResult);
        updateChart.setStrategy(GenChartStrategyEnum.GEN_MQ.getValue());
        updateChart.setExecMessage(inputCsvMessage);
        boolean b1 = chartService.updateById(updateChart);// 修改数据库状态为执行完成
        if (!b1) {
            channel.basicNack(deliveryTag, false, false);
            handleChartUpdateError(chart.getId(), "图表状态更改失败");
            return;
        }

        // 消息确认 手动
        channel.basicAck(deliveryTag, false);

    }


    //指定程序监听的消息队列和确认机制
    @SneakyThrows   // 抛异常
    @RabbitListener(queues = {BiMqConstant.WENXIN_QUEUE_NAME}, ackMode = "MANUAL")
    public void receiveMessageByWenxin(String message, Channel channel, @Header(AmqpHeaders.DELIVERY_TAG) long deliveryTag) {
        if (StringUtils.isBlank(message)) {
            /* 消息拒绝（标签，拒绝该标签的所有信息，true被拒绝的消息将重新排队false直接丢弃） */
            channel.basicNack(deliveryTag, false, false);
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "消息为空");
        }
        Long chartId = Long.parseLong(message);     // String转Long
        Chart chart = chartService.getById(chartId);
        if (chart == null) {
            channel.basicNack(deliveryTag, false, false);
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR, "图表为空");
        }
        //先修改图表任务状念为”执行中”。等执行成功后，修收为”已完成”、保执行钻米；执行失败斤，状修收为”双，记录任务失败信园：
        Chart updateChart = new Chart();
        updateChart.setId(chart.getId());
        updateChart.setStatus(FileConstant.RUNNING);
        boolean b = chartService.updateById(updateChart);   // 修改数据库状态为执行中
        if (!b) {
            channel.basicNack(deliveryTag, false, false);
            handleChartUpdateError(chart.getId(), "图表状态更改失败");
            return;
        }

        // 调用 AI
        log.info("调用 文心一言AI");
        String inputCsvMessage = buildUserInput(chart);
        String result = wenxinManager.doChatByWenxin(inputCsvMessage, chart.getUserId());
        if (result == null) {
            handleChartUpdateError(chart.getId(), "AI 生成错误空");
        }
        // String result = "#######sh#######ide";
        log.info("AI 生成的语句：\n{}", result);
        String[] splits = result.split("#######");
        if (splits.length != 3) {
            channel.basicNack(deliveryTag, false, false);
            handleChartUpdateError(chart.getId(), "AI 生成错误");
            return;
        }

        // 第一段是空，所以从第二段开始取
        String genChart = splits[1].trim();
        String genResult = splits[2].trim();
        genChart = ChartUtil.compressJson(genChart);

        updateChart.setStatus(FileConstant.SUCCEED);
        updateChart.setGenChart(genChart);
        updateChart.setGenResult(genResult);
        updateChart.setStrategy(GenChartStrategyEnum.GEN_MQ.getValue());
        updateChart.setExecMessage(inputCsvMessage);
        boolean b1 = chartService.updateById(updateChart);// 修改数据库状态为执行完成
        if (!b1) {
            channel.basicNack(deliveryTag, false, false);
            handleChartUpdateError(chart.getId(), "图表状态更改失败");
            return;
        }

        // 消息确认 手动
        channel.basicAck(deliveryTag, false);

    }

    /**
     * 构建用户输入
     * @param chart
     * @return
     */
    private String buildUserInput(Chart chart){
        String goal = chart.getGoal();
        String chartType = chart.getChartType();
        String csvData = String.valueOf(chartService.selectCsvData(chart.getId()));
        // String csvData = chart.getChartData();

        //用户输入
        StringBuilder userInput = new StringBuilder();
        userInput.append("分析需求：").append("\n");

        /**
         * 拼接分析目标
         */
        String userGoal = goal;
        if (StringUtils.isNotBlank(chartType)){
            userGoal += "，请使用" + chartType;
        }
        userInput.append(userGoal).append("\n");
        userInput.append("原始数据：").append("\n");
        //压缩后的数据（转换为csv格式）
        userInput.append(csvData).append("\n");

        return userInput.toString();
    }

    private void handleChartUpdateError(long chartId,String execMessage) {
        Chart updateChartResult = new Chart();
        updateChartResult.setId(chartId);
        updateChartResult.setStatus(FileConstant.FAILED);
        boolean updateResult = chartService.updateById(updateChartResult);
        if (!updateResult) {
            log.error("更新图表为失败状态 失败" + chartId + "," + execMessage);
        }
    }

}
